package zuochengyun;

/**
 * 字符串的调整和替换
 * 比如把空格替换成%20
 * 把给定的字符全部移至最左边或者最右边
 * 或者对字符串进行旋转
 * @author Administrator
 */
public class StringReplaceAndChange {

	public String replaceTab(String str){
		if( str == null || str.length() <= 0){
			return str;
		}
		int strLength = str.length();
		//首先确定字符数组的空间
		int tabCount = 0;
		for (int i = 0; i < strLength; i++) {
			if(str.charAt(i) == ' '){
				tabCount++;
			}
		}
		int length = strLength + 2 * tabCount;
		char[] chars = new char[length];
		int j = chars.length - 1;
		for (int i = length; i >= 0; i--) {
			if(str.charAt(i) == ' '){
				chars[j--] = '0';
				chars[j--] = '2';
				chars[j--] = '%';
			}else{
				chars[j--] = str.charAt(i);
			}
		}
		return String.valueOf(chars);
	}
	
	/**
	 * 翻转字符串,比如ABCDE，size = 3，翻转之后为DEABC 
	 */
	public void rotateWord(char[] chars, int size){
		if(chars == null || chars.length <= 0){
			return;
		}
		reverseString(chars, 0, size - 1);
		reverseString(chars, size, chars.length - 1);
		reverseString(chars, 0, chars.length - 1);
	}

	public void reverseString(char[] chars, int start, int end) {
		char temp = 0;
		while(start < end){
			temp = chars[start];
			chars[start] = chars[end];
			chars[end] = temp;
			start++;
			end--;
		}
	}
}
